<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="public, max-age=3600">
    <meta name="theme-color" content="#667eea">
    <title>数据提交 - 项目管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" media="print" onload="this.media='all'">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet" media="print" onload="this.media='all'">
    <link href="../styles/optimized.css" rel="stylesheet">
    <noscript>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    </noscript>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .container {
            max-width: 700px;
            padding: 50px;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
            animation: fadeInDown 1s ease-out 0.3s both;
        }

        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .project-title {
            font-size: 2.8rem;
            font-weight: 700;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 20px;
            position: relative;
        }

        .project-title::after {
            content: '';
            position: absolute;
            bottom: -10px;
            left: 50%;
            transform: translateX(-50%);
            width: 80px;
            height: 4px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 2px;
        }

        .project-description {
            font-size: 1.3rem;
            color: #666;
            margin-bottom: 30px;
            line-height: 1.8;
            font-weight: 400;
        }

        .project-image {
            text-align: center;
            margin-bottom: 40px;
            animation: zoomIn 0.8s ease-out 0.5s both;
            overflow: hidden;
        }

        @keyframes zoomIn {
            from {
                opacity: 0;
                transform: scale(0.8);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        .project-image img {
            width: 100%;
            height: auto;
            /* max-height: 420px; removed to allow taller images on larger screens */
            object-fit: contain;
            /* border-radius: 20px; */
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
            border: 3px solid rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
        }

        .project-image img:hover {
            transform: scale(1.05);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
        }


        .form-section {
            background: rgba(248, 249, 250, 0.8);
            backdrop-filter: blur(10px);
            padding: 40px;
            border-radius: 20px;
            margin-top: 30px;
            border: 1px solid rgba(233, 236, 239, 0.5);
            animation: fadeInUp 0.8s ease-out 0.7s both;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 10px;
            font-size: 1.1rem;
        }

        .form-control, .form-select {
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            padding: 15px 18px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(5px);
        }

        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.15);
            background: white;
            transform: translateY(-2px);
        }

        .form-control:hover, .form-select:hover {
            border-color: #b8c5f2;
            transform: translateY(-1px);
        }

        .mb-3 {
            margin-bottom: 30px;
            animation: slideInLeft 0.6s ease-out;
        }

        .mb-3:nth-child(even) {
            animation: slideInRight 0.6s ease-out;
        }

        @keyframes slideInLeft {
            from {
                opacity: 0;
                transform: translateX(-30px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(30px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .submit-container {
            text-align: center;
            margin-top: 50px;
            padding-top: 40px;
            border-top: 2px solid rgba(233, 236, 239, 0.5);
            animation: fadeInUp 0.8s ease-out 1s both;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            padding: 18px 40px;
            font-size: 18px;
            font-weight: 600;
            border-radius: 50px;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            position: relative;
            overflow: hidden;
        }

        .btn-primary::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
            transition: left 0.5s;
        }

        .btn-primary:hover::before {
            left: 100%;
        }

        .btn-primary:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 30px rgba(102, 126, 234, 0.4);
        }

        .btn-primary:active {
            transform: translateY(-1px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }

        .success-message {
            display: none;
            text-align: center;
            padding: 40px;
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            color: #155724;
            border-radius: 20px;
            margin-top: 40px;
            box-shadow: 0 15px 30px rgba(21, 87, 36, 0.15);
            border: 2px solid rgba(184, 218, 204, 0.5);
            animation: bounceIn 0.8s ease-out;
        }

        @keyframes bounceIn {
            0% {
                opacity: 0;
                transform: scale(0.3);
            }
            50% {
                opacity: 1;
                transform: scale(1.05);
            }
            70% {
                transform: scale(0.9);
            }
            100% {
                opacity: 1;
                transform: scale(1);
            }
        }

        .success-message h4 {
            font-weight: 700;
            margin-bottom: 20px;
            font-size: 1.8rem;
        }

        .loading-container {
            text-align: center;
            padding: 60px 20px;
        }

        .spinner-border {
            width: 4rem;
            height: 4rem;
            border-width: 0.4em;
            color: #667eea;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .loading-text {
            margin-top: 25px;
            font-size: 1.2rem;
            color: #666;
            font-weight: 500;
            animation: pulse 2s ease-in-out infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.6; }
        }

        .error-message {
            background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
            color: #721c24;
            padding: 25px;
            border-radius: 20px;
            margin: 25px 0;
            border: 2px solid rgba(241, 176, 183, 0.5);
            text-align: center;
            font-weight: 500;
            animation: shake 0.5s ease-in-out;
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-5px); }
            75% { transform: translateX(5px); }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                margin: 10px;
                padding: 30px 25px;
                border-radius: 20px;
            }
            
            .project-title {
                font-size: 2.2rem;
            }
            
            .project-description {
                font-size: 1.1rem;
            }
            
            /* .project-image {
                margin-left: 16px;
                margin-right: 16px;
            } */
            
            .project-image img {
                width: 100%;
                height: auto;
                /* remove max-height to allow long images to fill width */
            }
            
            .form-section {
                padding: 25px;
            }
            
            .btn-primary {
                padding: 15px 30px;
                font-size: 16px;
            }
        }
        
        @media (max-width: 480px) {
            .project-image {
                margin-left: 16px;
                margin-right: 16px;
            }
            
            .project-image img {
                width: 100%;
                height: auto;
                /* remove max-height to allow long images to fill width */
            }
            
            .project-title {
                font-size: 1.8rem;
            }
            
            .container {
                padding: 20px 15px;
            }
        }

        /* 滚动条样式 */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div id="projectInfo" style="display: none;">
                <h1 id="projectName" class="project-title">数据提交表单</h1>
                <div id="projectImage" class="project-image" style="display: none;">
                    <img id="projectMainImage" src="" alt="项目图片" class="img-fluid" loading="lazy">
                </div>
                <p id="projectDescription" class="project-description">请填写以下信息并提交</p>
            </div>
            <div id="defaultHeader">
                <h1 class="project-title">数据提交表单</h1>
                <p class="project-description">请填写以下信息并提交</p>
            </div>
        </div>
        
        <div id="loadingMessage" class="loading-container">
            <div class="spinner-border" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="loading-text">正在加载项目信息...</p>
        </div>
        
        <div id="formContainer" style="display: none;">
            <div class="form-section">
                <form id="submissionForm">
                    <div id="formFields">
                        <!-- 动态生成的表单字段将在这里显示 -->
                    </div>
                </form>
            </div>
            <div class="submit-container">
                <button type="submit" form="submissionForm" class="btn btn-primary">
                    <i class="bi bi-send me-2"></i>
                    提交数据
                </button>
            </div>
        </div>
        
        <div id="successMessage" class="success-message">
            <h4>
                <i class="bi bi-check-circle me-2"></i>
                提交成功！
            </h4>
            <p>您的信息已成功提交，感谢您的参与。</p>
        </div>
    </div>

    <script>
        // 注册Service Worker
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('/sw.js')
                    .then(registration => {
                        console.log('SW registered: ', registration);
                    })
                    .catch(registrationError => {
                        console.log('SW registration failed: ', registrationError);
                    });
            });
        }

        let formConfig = null;
        let project = null;
        
        // 通用URL参数解析（支持search与hash）
        function getParamFromUrl(names) {
            const url = new URL(window.location.href);
            const searchParams = url.searchParams;
            const hashParams = new URLSearchParams(url.hash.replace(/^#/, ''));
            for (const name of names) {
                const v = searchParams.get(name) || hashParams.get(name);
                if (v) return v;
            }
            return null;
        }
        
        // 从URL获取项目ID或分享令牌（兼容多命名）
        function getProjectIdFromUrl() {
            return getParamFromUrl(['projectId', 'pid', 'id']);
        }
        
        function getShareTokenFromUrl() {
            return getParamFromUrl(['share', 'shareToken', 'token', 't']);
        }
        
        // 带重试与超时的fetch工具
        async function fetchWithRetry(url, options = {}, retries = 2, timeoutMs = 10000) {
            for (let attempt = 0; attempt <= retries; attempt++) {
                const controller = new AbortController();
                const id = setTimeout(() => controller.abort(), timeoutMs);
                try {
                    const resp = await fetch(url, { ...options, signal: controller.signal });
                    clearTimeout(id);
                    // 对 408/429/5xx 进行重试
                    if (!resp.ok && [408,429,500,502,503,504].includes(resp.status) && attempt < retries) {
                        await new Promise(r => setTimeout(r, 500 * (attempt + 1)));
                        continue;
                    }
                    return resp;
                } catch (err) {
                    clearTimeout(id);
                    if (attempt < retries) {
                        await new Promise(r => setTimeout(r, 500 * (attempt + 1)));
                        continue;
                    }
                    throw err;
                }
            }
        }
        
        // 自适应接口前缀：优先 ''，失败（404/网络/CORS）时回退到 '/api'
        async function fetchWithAdaptiveBase(path, options = {}, retries = 2, timeoutMs = 10000) {
            // 先尝试无前缀
            try {
                const resp = await fetchWithRetry(path, options, retries, timeoutMs);
                if (resp && resp.ok) return resp;
                // 404 或其他非OK再尝试 /api 前缀
                const respApi = await fetchWithRetry(`/api${path}`, options, retries, timeoutMs);
                return respApi;
            } catch (e) {
                // 网络或超时错误，回退到 /api
                return fetchWithRetry(`/api${path}`, options, retries, timeoutMs);
            }
        }
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadProjectAndForm();
        });
        
        // 加载项目信息和表单配置
        async function loadProjectAndForm() {
            const shareToken = getShareTokenFromUrl();
            const projectId = getProjectIdFromUrl();
            
            if (!shareToken && !projectId) {
                alert('无效的项目链接，请重新扫描二维码');
                return;
            }
            
            // 如果离线，直接提示
            if (!navigator.onLine) {
                document.getElementById('loadingMessage').innerHTML = '<p class="text-danger">当前网络不可用，请检查网络后重试</p>';
                return;
            }
            
            try {
                let response;
                if (shareToken) {
                    // 通过分享令牌获取项目信息（带重试+前缀自适应）
                    response = await fetchWithAdaptiveBase(`/project-shares/token/${shareToken}`);
                } else {
                    // 通过项目ID获取项目信息（带重试+前缀自适应）
                    response = await fetchWithAdaptiveBase(`/projects/${projectId}`);
                }
                
                if (!response.ok) {
                    throw new Error('获取项目信息失败');
                }
                
                const data = await response.json();
                project = shareToken ? data.project : data;
                formConfig = project.formConfig;
                
                // 调试信息
                console.log('项目数据:', project);
                console.log('表单配置:', formConfig);
                if (project && project.fieldTypes) {
                    console.log('项目字段类型:', project.fieldTypes);
                }
                if (formConfig && formConfig.fieldTypes) {
                    console.log('表单配置字段类型:', formConfig.fieldTypes);
                }
                
                // 显示项目信息
                displayProjectInfo(project);
                
                generateForm();
            } catch (error) {
                console.error('加载项目信息失败:', error);
                document.getElementById('loadingMessage').innerHTML = '<p class="text-danger">加载失败，请重新扫描二维码或稍后重试</p>';
            }
        }
        
        // 显示项目信息
        function displayProjectInfo(project) {
            const projectInfo = document.getElementById('projectInfo');
            const defaultHeader = document.getElementById('defaultHeader');
            const projectName = document.getElementById('projectName');
            const projectDescription = document.getElementById('projectDescription');
            const projectImage = document.getElementById('projectImage');
            const projectMainImage = document.getElementById('projectMainImage');
            
            if (project.name) {
                projectName.textContent = project.name;
                projectDescription.innerHTML = project.description || '请填写以下信息并提交';
                
                // 显示项目图片
                if (project.mainImage) {
                    projectMainImage.src = project.mainImage;
                    projectImage.style.display = 'block';
                }
                
                // 显示项目信息，隐藏默认标题
                projectInfo.style.display = 'block';
                defaultHeader.style.display = 'none';
            }
        }
        
        // 生成动态表单
        function generateForm() {
            const formFields = document.getElementById('formFields');
            const loadingMessage = document.getElementById('loadingMessage');
            const submissionForm = document.getElementById('submissionForm');
            
            // 默认字段配置
            const defaultFields = {
                name: { label: '姓名', type: 'text', required: true, sortOrder: 1 },
                phone: { label: '联系电话', type: 'tel', required: true, sortOrder: 2 },
                company: { label: '企业名称', type: 'text', required: false, sortOrder: 3 },
                personnel: { label: '参加项目人员', type: 'text', required: false, sortOrder: 4 },
                region: { label: '地区', type: 'text', required: false, sortOrder: 5 },
                industry: { label: '行业', type: 'select', required: false, sortOrder: 6, options: [
                    '制造业', '服务业', '科技', '金融', '教育', '医疗', '建筑', '零售', '物流', '农业', '其他'
                ]},
                message: { label: '留言内容', type: 'textarea', required: false, sortOrder: 7 }
            };
            
            let fieldsToShow = {};
            
            // 根据项目配置显示字段
            let fieldTypesToUse = null;
            
            // 优先使用project.fieldTypes（直接关联）
            if (project && project.fieldTypes && project.fieldTypes.length > 0) {
                fieldTypesToUse = project.fieldTypes;
            } 
            // 如果没有直接关联，则使用formConfig.fieldTypes
            else if (formConfig && formConfig.fieldTypes && formConfig.fieldTypes.length > 0) {
                fieldTypesToUse = formConfig.fieldTypes;
            }
            
            if (fieldTypesToUse) {
                // 按sortOrder排序字段类型
                const sortedFieldTypes = fieldTypesToUse
                    .filter(fieldType => fieldType.enabled)
                    .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
                
                // 根据排序后的fieldTypes生成字段
                sortedFieldTypes.forEach(fieldType => {
                    const customLabel = (formConfig && formConfig.fieldLabels && formConfig.fieldLabels[fieldType.key]) || fieldType.label;
                    fieldsToShow[fieldType.key] = {
                        label: customLabel,
                        type: fieldType.type,
                        required: fieldType.required,
                        options: fieldType.options || [],
                        sortOrder: fieldType.sortOrder || 0
                    };
                });
            } else {
                // 如果没有任何字段配置，则显示所有默认字段
                fieldsToShow = defaultFields;
            }
            
            // 生成表单字段HTML - 按sortOrder排序
            let formHTML = '';
            const sortedFieldNames = Object.keys(fieldsToShow).sort((a, b) => {
                const orderA = fieldsToShow[a].sortOrder || 0;
                const orderB = fieldsToShow[b].sortOrder || 0;
                return orderA - orderB;
            });
            
            sortedFieldNames.forEach(fieldName => {
                const field = fieldsToShow[fieldName];
                formHTML += `<div class="mb-3">`;
                formHTML += `<label for="${fieldName}" class="form-label">${field.label}</label>`;
                
                if (field.type === 'textarea') {
                    formHTML += `<textarea class="form-control" id="${fieldName}" rows="4" ${field.required ? 'required' : ''}></textarea>`;
                } else if (field.type === 'select') {
                    formHTML += `<select class="form-control" id="${fieldName}" ${field.required ? 'required' : ''}>`;
                    formHTML += `<option value="">请选择${field.label}</option>`;
                    field.options.forEach(option => {
                        formHTML += `<option value="${option}">${option}</option>`;
                    });
                    formHTML += `</select>`;
                } else {
                    formHTML += `<input type="${field.type}" class="form-control" id="${fieldName}" ${field.required ? 'required' : ''}>`;
                }
                
                formHTML += `</div>`;
            });
            
            formFields.innerHTML = formHTML;
            
            // 隐藏加载消息，显示表单
            loadingMessage.style.display = 'none';
            document.getElementById('formContainer').style.display = 'block';
        }

        // 表单提交处理
        document.getElementById('submissionForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const shareToken = getShareTokenFromUrl();
            const projectId = getProjectIdFromUrl();
            
            if (!shareToken && !projectId) {
                alert('无效的项目链接，请重新扫描二维码');
                return;
            }
            
            // 防重复提交：禁用按钮
            const submitBtn = document.querySelector('.submit-container button[form="submissionForm"]');
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>提交中...';
            }
            
            // 收集表单数据
            const formData = {};
            const formInputs = document.querySelectorAll('#formFields input, #formFields select, #formFields textarea');
            formInputs.forEach(input => {
                formData[input.id] = input.value;
            });
            
            const submissionData = {
                data: {
                    ...formData,
                    submittedAt: new Date().toISOString()
                }
            };
            
            try {
                let response;
                const postOptions = {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(submissionData)
                };
                if (shareToken) {
                    // 通过分享令牌提交（带重试+前缀自适应）
                    response = await fetchWithAdaptiveBase(`/submissions/share/${shareToken}`, postOptions, 1, 12000);
                } else {
                    // 通过项目ID提交（保持向后兼容）（带重试+前缀自适应）
                    response = await fetchWithAdaptiveBase(`/submissions/project/${projectId}`, postOptions, 1, 12000);
                }
                
                if (response.ok) {
                    // 显示成功消息
                    document.getElementById('formContainer').style.display = 'none';
                    document.getElementById('successMessage').style.display = 'block';
                } else {
                    const errorData = await response.json();
                    alert(`提交失败: ${errorData.message || '请稍后重试'}`);
                }
            } catch (error) {
                console.error('提交错误:', error);
                alert('提交时发生错误，请稍后重试');
            } finally {
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="bi bi-send me-2"></i>提交数据';
                }
            }
        });

    </script>
</body>
</html>